package com.admin_system.service.impl;

import com.admin_system.pojo.User;
import com.admin_system.mapper.UserMapper;
import com.admin_system.service.UserService;
import com.admin_system.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    @Lazy
    private BCryptPasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public User login(String account, String password) {
        // 尝试通过用户名登录
        User user = userMapper.findByUsername(account);
        
        // 如果用户名登录失败，尝试通过手机号登录
        if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
            // 尝试通过手机号查找用户
            user = userMapper.findByPhone(account);
            
            // 如果找到用户但密码不匹配，返回null
            if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
                return null;
            }
        }
        
        // 登录成功，更新最后登录时间
        updateLastLoginTime(user);
        return user;
    }
    
    @Override
    @Transactional
    public void register(User user) {
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        // 设置默认值
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        user.setIsActive(true);
        
        // 设置默认角色为普通用户
        if (user.getRole() == null) {
            user.setRole("ROLE_USER");
        }
        
        userMapper.insert(user);
    }
    
    @Override
    public boolean checkUsernameExists(String username) {
        return userMapper.countByUsername(username) > 0;
    }
    
    @Override
    public boolean checkPhoneExists(String phone) {
        // 检查手机号是否存在
        return userMapper.countByPhone(phone) > 0;
    }

    @Override
    public boolean checkEmailExists(String email) {
        // 检查邮箱是否存在
        return userMapper.countByEmail(email) > 0;
    }

    /**
     * 获取使用指定邮箱的用户数量
     * @param email 邮箱
     * @return 用户数量
     */
    @Override
    public int getUserCountByEmail(String email) {
        return userMapper.countByEmail(email);
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public User loginByUsername(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            updateLastLoginTime(user);
            return user;
        }
        return null;
    }

    @Override
    public User loginByPhone(String phone, String password) {
        User user = userMapper.findByPhone(phone);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            updateLastLoginTime(user);
            return user;
        }
        return null;
    }

    private void updateLastLoginTime(User user) {
        user.setLastLoginTime(new Timestamp(System.currentTimeMillis()));
        userMapper.updateLastLoginTime(user);
    }
    
    @Override
    @Transactional
    public boolean updateUserFullName(Integer userId, String fullName) {
        if (userId == null || fullName == null) {
            return false;
        }
        
        try {
            int rowsAffected = userMapper.updateUserFullName(userId, fullName);
            return rowsAffected > 0;
        } catch (Exception e) {
            throw new RuntimeException("更新用户真实姓名失败", e);
        }
    }
    
    @Override
    @Transactional
    public String generateUserToken(User user) {
        if (user == null) {
            return null;
        }
        
        // 生成新token
        String token = jwtTokenUtil.generateToken(user.getUsername(), user.getRole());
        
        // 保存token到数据库
        user.setLastToken(token);
        userMapper.updateUserToken(user.getId(), token);
        
        logger.info("为用户 {} 生成新的token", user.getUsername());
        return token;
    }
    
    @Override
    public boolean validateUserToken(String username, String token) {
        // 1. 校验token签名和有效期
        try {
            if (!jwtTokenUtil.validateToken(token, username)) {
                logger.info("token已过期或签名无效: {}", username);
                return false;
            }
        } catch (Exception e) {
            logger.warn("验证token时发生异常: {}, 错误: {}", username, e.getMessage());
            return false;
        }
        
        // 2. 校验token是否为最新
        User user = userMapper.findByUsername(username);
        if (user == null) {
            logger.warn("验证token时找不到用户: {}", username);
            return false;
        }
        
        if (token.equals(user.getLastToken())) {
            return true;
        } else if (user.getLastToken() == null) {
            logger.info("用户 {} 的数据库中token为空，可能已注销或重置", username);
            return false;
        } else {
            logger.info("用户 {} 的token与数据库中的不匹配，可能已在其他地方登录", username);
            return false;
        }
    }
    
    @Override
    @Transactional
    public void invalidateUserTokens(String username) {
        User user = userMapper.findByUsername(username);
        if (user != null) {
            // 清除用户的token
            userMapper.updateUserToken(user.getId(), null);
            logger.info("已使用户 {} 的所有token失效", username);
        }
    }

    /**
     * 通过邮箱重置用户密码
     * 
     * @param email 用户邮箱
     * @param newPassword 新密码（明文）
     * @return 重置成功返回true，失败返回false
     */
    @Override
    public boolean resetPasswordByEmail(String email, String newPassword) {
        // 通过邮箱查找用户
        List<User> users = userMapper.getUserByEmail(email);
        if (users == null || users.isEmpty()) {
            logger.warn("通过邮箱 {} 未找到用户", email);
            return false;
        }
        
        try {
            // 对新密码进行加密
            String encryptedPassword = passwordEncoder.encode(newPassword);
            
            boolean allSuccess = true;
            
            // 为所有匹配的用户更新密码
            for (User user : users) {
                // 更新用户密码
                int result = userMapper.updateUserPassword(user.getId(), encryptedPassword);
                
                if (result > 0) {
                    logger.info("用户 {} 的密码已成功重置", user.getUsername());
                    
                    // 使当前用户的所有令牌失效
                    invalidateUserTokens(user.getUsername());
                } else {
                    logger.warn("用户 {} 的密码重置失败", user.getUsername());
                    allSuccess = false;
                }
            }
            
            return allSuccess;
        } catch (Exception e) {
            logger.error("重置密码出错", e);
            return false;
        }
    }

    /**
     * 获取活跃用户总数
     * @return 活跃用户总数
     */
    @Override
    public int countActiveUsers() {
        return userMapper.countTotal();
    }
}